package com.itheima.bakery.demos.web.Repositories;
import com.itheima.bakery.demos.web.model.CartItem;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.List;
import java.util.Optional;
import java.util.Set;

@Repository
public interface CartItemRepository extends JpaRepository<CartItem, Integer> {
    // 根据用户ID查询购物车项
    List<CartItem> findByUser_Id(Integer userId);

    List<CartItem> findByIdIn(List<Integer> cartItemIds);
    // 根据用户ID和产品ID查询购物车项
    Optional<CartItem> findByUser_IdAndProduct_Id(Integer userId, Integer productId);

    Optional<CartItem> findByUser_IdAndId(Integer userId, Integer cartItemId);

    // 根据用户ID删除所有购物车项
    @Modifying
    @Transactional
    @Query("DELETE FROM CartItem c WHERE c.user.id = :userId")
    void deleteByUserId(@Param("userId") Integer userId);

    // 根据用户ID计算小计总和
    @Modifying
    @Transactional
    @Query("SELECT SUM(c.subtotal) FROM CartItem c WHERE c.user.id = :userId")
    BigDecimal sumSubtotalByUserId(@Param("userId") Integer userId);

    @Modifying
    @Transactional
    @Query("DELETE FROM CartItem c WHERE c.user.id = :userId AND c.product.id IN :productIds")
    void deleteByUserIdAndProductIds(@Param("userId") Integer userId, @Param("productIds") Set<Integer> productIds);
}